package org.jeecg.modules.xl.exceltemplate.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.xl.customerType.entity.XlCustomerPurchaseUser;
import org.jeecg.modules.xl.customerType.entity.XlCustomerType;
import org.jeecg.modules.xl.customerType.service.IXlCustomerPurchaseUserService;
import org.jeecg.modules.xl.customerType.service.IXlCustomerTypeService;
import org.jeecg.modules.xl.exceltemplate.service.ExcelTemplateService;
import org.jeecg.modules.xl.exceltemplate.vo.*;
import org.jeecg.modules.xl.kuaidi100.entity.XlKuaidi100Logicom;
import org.jeecg.modules.xl.kuaidi100.service.IXlKuaidi100LogicomService;
import org.jeecg.modules.xl.order.vo.OrderSheet;
import org.jeecg.modules.xl.order.vo.OrderSheetDetail;
import org.jeecg.modules.xl.order.vo.ProductSheet;
import org.jeecg.modules.xl.order.vo.StoreSheet;
import org.jeecg.modules.xl.product.entity.XlProductInfo;
import org.jeecg.modules.xl.product.service.IXlProductCustomerPriceService;
import org.jeecg.modules.xl.product.service.IXlProductInfoService;
import org.jeecg.modules.xl.producttype.entity.XlProductType;
import org.jeecg.modules.xl.producttype.service.IXlProductTypeService;
import org.jeecg.modules.xl.store.entity.XlCustomerStoreInfo;
import org.jeecg.modules.xl.store.service.IXlCustomerMystoreService;
import org.jeecg.modules.xl.store.service.IXlCustomerStoreInfoService;
import org.jeecg.modules.xl.store.vo.XlCustomerStoreImportVO;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 模版下载service
 *
 * @author deco
 * @create 2024-10-30
 */
@Service
public class ExcelTemplateServiceImpl implements ExcelTemplateService {
    @Autowired
    private IXlCustomerMystoreService xlCustomerMystoreService;
    @Autowired
    private IXlProductInfoService productInfoService;
    @Autowired
    private IXlCustomerStoreInfoService xlCustomerStoreInfoService;
    @Autowired
    private IXlProductTypeService xlProductTypeService;
    @Autowired
    private IXlKuaidi100LogicomService kuaidi100LogicomService;

    @Autowired
    private IXlProductInfoService xlProductInfoService;

    @Autowired
    private IXlCustomerTypeService customerTypeService;

    @Autowired
    private IXlCustomerPurchaseUserService xlCustomerPurchaseUserService;

    @Autowired
    private IXlProductCustomerPriceService xlProductCustomerPriceService;

    @Override
    public ModelAndView createOrderTemplate() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //组装sheet
        //多个map，对应了多个sheet
        List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();

        ExportParams orderSheetParams = new ExportParams("订单导入模版", "导入人:" + sysUser.getRealname(),"订单导入模版");
        orderSheetParams.setType(ExcelType.XSSF);
        Map<String, Object> orderSheet = new HashMap<>();
        orderSheet.put(NormalExcelConstants.CLASS, OrderSheet.class);
        orderSheet.put(NormalExcelConstants.PARAMS, orderSheetParams);

        List orderDetaillist = new ArrayList<OrderSheetDetail>();

        //模拟订单1，2个明细
        OrderSheet orderTemp1 = new OrderSheet();
        orderTemp1.setOrderCode("CG2349814124435");
        orderTemp1.setStoreCode("门边编码1");
        orderTemp1.setOrderNotes("示例数据，导入时请删除这个订单");
        List orderDetaillist1   = new ArrayList<OrderSheetDetail>();
        OrderSheetDetail detail1 = new OrderSheetDetail();
        detail1.setProductId("示例数据-" + RandomUtil.randomNumbers(8));
        detail1.setUpcCode("6903244370899");
        orderDetaillist1.add(detail1);
        OrderSheetDetail detail2 = new OrderSheetDetail();
        detail2.setProductId("示例数据-" + RandomUtil.randomNumbers(8));
        detail2.setUpcCode("6922731800701");
        orderDetaillist1.add(detail2);
        orderTemp1.setOrderDetail(orderDetaillist1);

        //模拟订单2 1个明细
        OrderSheet orderTemp2 = new OrderSheet();
        orderTemp2.setOrderCode("CG2349814124435");
        orderTemp2.setStoreCode("门边编码2");
        orderTemp2.setOrderNotes("示例数据，导入时请删除这个订单");
        List orderDetaillist2   = new ArrayList<OrderSheetDetail>();
        orderDetaillist2.add(detail2);
        orderTemp2.setOrderDetail(orderDetaillist2);

        List orderSheetLisst   = new ArrayList<OrderSheet>();
        orderSheetLisst.add(orderTemp1);
        orderSheetLisst.add(orderTemp2);

        orderSheet.put(NormalExcelConstants.DATA_LIST, orderSheetLisst);
        listMap.add(orderSheet);

        //构造门店清单sheet
        List<XlCustomerStoreInfo> storeList  = new ArrayList<>();
        if(isAdmin()){
            //如果是管理员或作其他需要查询全部门店的账户，就直接返回全部门店
            QueryWrapper<XlCustomerStoreInfo> ss= new QueryWrapper<>();
            ss.eq("is_deleted",0);
            storeList.addAll(xlCustomerStoreInfoService.list());
        }else{
            //查询我的门店
            //QueryWrapper<XlCustomerStoreInfo> queryWrapper = QueryGenerator.initQueryWrapper(xlCustomerStoreInfo, req.getParameterMap());
            QueryWrapper<XlCustomerStoreInfo> queryWrapper =new QueryWrapper<>();
            queryWrapper.eq("user_account", sysUser.getUsername());
            queryWrapper.eq("is_deleted",0);
            storeList.addAll(xlCustomerMystoreService.selectStoresByUserId2(queryWrapper));
        }
        List<StoreSheet> storeSheetlist = storeList.stream().map(storeInfo->new StoreSheet(storeInfo.getStoreCode(),storeInfo.getStoreName()))
                .collect(Collectors.toList());

        Map<String, Object> storeSheet = new HashMap<String, Object>();
        ExportParams storeSheetParams = new ExportParams("门店清单","门店清单",ExcelType.XSSF);
        storeSheet.put(NormalExcelConstants.CLASS, StoreSheet.class);
        storeSheet.put(NormalExcelConstants.PARAMS, storeSheetParams);
        //导出登录人名下的所有门店ID
        storeSheet.put(NormalExcelConstants.DATA_LIST, storeSheetlist);
        listMap.add(storeSheet);

        //商品清单

        Map<String, Object> productSheet = new HashMap<String, Object>();
        ExportParams productSheetparam = new ExportParams("商品清单","商品清单",ExcelType.XSSF);
        productSheet.put(NormalExcelConstants.CLASS, XlProductInfo.class);
        productSheet.put(NormalExcelConstants.PARAMS, productSheetparam);
        //导出系统之所有的商品清单
        List productList = new ArrayList();
        if(isAdmin()) {
            //如果是管理员或作其他二线角色要导出模版，那价格为空
            //productList.addAll(productInfoService.getProductListForExport());
            List<XlProductInfo> ss=  productInfoService.list();
            productList.addAll(ss);
        }else{
            //如果是其他角色，就导出xl_customer_purchase_user 关系下的商品数据
            QueryWrapper<XlCustomerPurchaseUser> xlCustomerPurchaseUserQueryWrapper = new QueryWrapper<>();
            xlCustomerPurchaseUserQueryWrapper.eq("phone", sysUser.getPhone());
            XlCustomerPurchaseUser  xlCustomerPurchaseUser = xlCustomerPurchaseUserService.getOne(xlCustomerPurchaseUserQueryWrapper);
            if(ObjectUtil.isNotEmpty(xlCustomerPurchaseUser)){
                QueryWrapper<XlProductInfo> xlProductInfoQueryWrapper = new QueryWrapper<>();
                xlProductInfoQueryWrapper.eq("type",xlCustomerPurchaseUser.getCustomerTypeCode());//不存在的数据库字段，需要手动设
                Page<XlProductInfo> page = new Page<XlProductInfo>(1, 300);
                IPage<XlProductInfo> pageList = xlProductCustomerPriceService.queryListByPage(page,xlProductInfoQueryWrapper);
                if(ObjectUtil.isNotEmpty(pageList)){
                    productList.addAll(pageList.getRecords());
                }
            }

        }
        //下载模版里的文件 是哪个渠道
        productSheet.put(NormalExcelConstants.DATA_LIST, productList);
        listMap.add(productSheet);

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // Step.4 AutoPoi 导出Excel
        mv.addObject(NormalExcelConstants.FILE_NAME, "订单导入模版");
        mv.addObject(NormalExcelConstants.MAP_LIST,listMap);
        return mv;
    }

    @Override
    public ModelAndView productImportTemplate() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //多个map，对应了多个sheet
        List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
        //商品管理sheet
        ExportParams productSheetParams = new ExportParams("商品导入模版", "导入人:" + sysUser.getRealname(),"商品导入模版");
        productSheetParams.setType(ExcelType.XSSF);
        Map<String, Object> productSheet = new HashMap<>();
        productSheet.put(NormalExcelConstants.CLASS, XlProductInfo.class);
        productSheet.put(NormalExcelConstants.PARAMS, productSheetParams);
        XlProductInfo  xlProductInfo = new XlProductInfo ();
        List productSheetList   = new ArrayList<XlProductInfo>();
        productSheet.put(NormalExcelConstants.DATA_LIST, productSheetList);
        listMap.add(productSheet);

        //商品类目sheet
        ExportParams productTypeSheetParams = new ExportParams("商品类目", "导入人:" + sysUser.getRealname(),"商品类目");

        productTypeSheetParams.setType(ExcelType.XSSF);
        Map<String, Object> productTypeSheet = new HashMap<>();
        productTypeSheet.put(NormalExcelConstants.CLASS, ProductTypeVo.class);
        productTypeSheet.put(NormalExcelConstants.PARAMS, productTypeSheetParams);
        List productTypeSheetList   = xlProductTypeService.queryProductTypeSheetList();
        productTypeSheet.put(NormalExcelConstants.DATA_LIST, productTypeSheetList);
        listMap.add(productTypeSheet);

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // Step.4 AutoPoi 导出Excel
        mv.addObject(NormalExcelConstants.FILE_NAME, "商品导入模版");//没用，前段会在设置
        mv.addObject(NormalExcelConstants.MAP_LIST,listMap);
        return mv;

    }

    @Override
    public ModelAndView storeImportTemplate() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //多个map，对应了多个sheet
        List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
        //商品管理sheet
        ExportParams storeSheetParams = new ExportParams("门店导入模版", "导入人:" + sysUser.getRealname(),"门店导入模版");
        storeSheetParams.setType(ExcelType.XSSF);
        Map<String, Object> storeSheet = new HashMap<>();
        storeSheet.put(NormalExcelConstants.CLASS, XlCustomerStoreImportVO.class);
        storeSheet.put(NormalExcelConstants.PARAMS, storeSheetParams);
        List productSheetList   = new ArrayList<XlProductInfo>();
        storeSheet.put(NormalExcelConstants.DATA_LIST, productSheetList);
        listMap.add(storeSheet);


        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // Step.4 AutoPoi 导出Excel
        mv.addObject(NormalExcelConstants.FILE_NAME, "门店导入模版");
        mv.addObject(NormalExcelConstants.MAP_LIST,listMap);
        return mv;
    }

    @Override
    public ModelAndView deliveryCodeImportTemplate() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //多个map，对应了多个sheet
        List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
        //发货单sheet
        ExportParams deliveryCodeSheetParams = new ExportParams("快递单回传模版", "导入人:" + sysUser.getRealname(),"快递单回传模版");
        deliveryCodeSheetParams.setType(ExcelType.XSSF);
        Map<String, Object> deliveryCodeSheet = new HashMap<>();
        deliveryCodeSheet.put(NormalExcelConstants.CLASS, DeliveryCodeSheet.class);
        deliveryCodeSheet.put(NormalExcelConstants.PARAMS, deliveryCodeSheetParams);
        deliveryCodeSheet.put(NormalExcelConstants.DATA_LIST, new ArrayList<DeliveryCodeSheet>());
        listMap.add(deliveryCodeSheet);

        //快递公司编码sheet
        ExportParams compSheetParams = new ExportParams("快递公司编码", "导入人:" + sysUser.getRealname(),"快递公司编码");
        compSheetParams.setType(ExcelType.XSSF);
        Map<String, Object> compSheet = new HashMap<>();
        compSheet.put(NormalExcelConstants.CLASS, DeliveryCompSheet.class);
        compSheet.put(NormalExcelConstants.PARAMS, compSheetParams);
        List delicopmList = new ArrayList<DeliveryCodeSheet>();

        List<XlKuaidi100Logicom> xlKuaidi100LogicomList = kuaidi100LogicomService.list();
        for(XlKuaidi100Logicom xlKuaidi100Logicom: xlKuaidi100LogicomList){
            delicopmList.add(new DeliveryCompSheet(xlKuaidi100Logicom.getComCode(),xlKuaidi100Logicom.getComName()));
        }
        compSheet.put(NormalExcelConstants.DATA_LIST, delicopmList);
        listMap.add(compSheet);

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // Step.4 AutoPoi 导出Excel
        mv.addObject(NormalExcelConstants.FILE_NAME, "快递单回传模版");//没用，前段会在设置
        mv.addObject(NormalExcelConstants.MAP_LIST,listMap);
        return mv;
    }

    @Override
    public ModelAndView getImportAfterOrderTemplate() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //多个map，对应了多个sheet
        List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
        //售后单sheet
        ExportParams afterOrderImportParams = new ExportParams("售后单", "导入人:" + sysUser.getRealname(),"售后单上传模版");
        afterOrderImportParams.setType(ExcelType.XSSF);
        Map<String, Object> afterOrderImportSheet = new HashMap<>();
        afterOrderImportSheet.put(NormalExcelConstants.CLASS, AfterOrderImportVO.class);
        afterOrderImportSheet.put(NormalExcelConstants.PARAMS, afterOrderImportParams);
        afterOrderImportSheet.put(NormalExcelConstants.DATA_LIST, new ArrayList<AfterOrderImportVO>());
        listMap.add(afterOrderImportSheet);

        //售后类型sheet
        ExportParams afterTypeSheetParams = new ExportParams("售后类型", "导出人:" + sysUser.getRealname(),"售后类型");
        afterTypeSheetParams.setType(ExcelType.XSSF);
        Map<String, Object> afterTypeSheet = new HashMap<>();
        afterTypeSheet.put(NormalExcelConstants.CLASS, AfterOrderTypeVO.class);
        afterTypeSheet.put(NormalExcelConstants.PARAMS, afterTypeSheetParams);
        List afterOrderTypeList = new ArrayList<AfterOrderTypeVO>();
        afterOrderTypeList.add(new AfterOrderTypeVO("1","退货退款"));
        afterOrderTypeList.add(new AfterOrderTypeVO("2","不退货退款"));
        afterOrderTypeList.add(new AfterOrderTypeVO("3","退货不退款"));
        afterOrderTypeList.add(new AfterOrderTypeVO("4","搭赠"));
        afterOrderTypeList.add(new AfterOrderTypeVO("5","库存不足"));
        afterTypeSheet.put(NormalExcelConstants.DATA_LIST, afterOrderTypeList);
        listMap.add(afterTypeSheet);


        //售后原因sheet
        ExportParams afterReasonSheetParams = new ExportParams("售后原因", "导入人:" + sysUser.getRealname(),"售后原因");
        afterReasonSheetParams.setType(ExcelType.XSSF);
        Map<String, Object> afterReasonSheet = new HashMap<>();
        afterReasonSheet.put(NormalExcelConstants.CLASS, AfterReasonTypeVo.class);
        afterReasonSheet.put(NormalExcelConstants.PARAMS, afterReasonSheetParams);
        List afterOrderReasonList = new ArrayList<AfterReasonTypeVo>();
        afterOrderReasonList.add(new AfterReasonTypeVo("1","多发"));
        afterOrderReasonList.add(new AfterReasonTypeVo("2","包装破损"));
        afterOrderReasonList.add(new AfterReasonTypeVo("3","少发、漏发、错发"));
        afterOrderReasonList.add(new AfterReasonTypeVo("4","搭赠"));
        afterOrderReasonList.add(new AfterReasonTypeVo("5","库存不足"));
        afterReasonSheet.put(NormalExcelConstants.DATA_LIST, afterOrderReasonList);
        listMap.add(afterReasonSheet);


        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // Step.4 AutoPoi 导出Excel
        mv.addObject(NormalExcelConstants.FILE_NAME, "售后单上传");//没用，前段会在设置
        mv.addObject(NormalExcelConstants.MAP_LIST,listMap);
        return mv;
    }

    @Override
    public ModelAndView prodcutcustomerimport() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //多个map，对应了多个sheet
        List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();

        //渠道商品sheet
        ExportParams customerProductPara = new ExportParams("渠道商品导入", "导入人:" + sysUser.getRealname(),"渠道商品导入");
        customerProductPara.setType(ExcelType.XSSF);
        Map<String, Object> customerProductSheet = new HashMap<>();
        customerProductSheet.put(NormalExcelConstants.CLASS, ProductCustomer.class);
        customerProductSheet.put(NormalExcelConstants.PARAMS, customerProductPara);
        customerProductSheet.put(NormalExcelConstants.DATA_LIST, new ArrayList<ProductCustomer>());
        listMap.add(customerProductSheet);

        //商品主档
        ExportParams productMainParam = new ExportParams("商品主档", "导出人:" + sysUser.getRealname(),"商品主档");
        productMainParam.setType(ExcelType.XSSF);
        Map<String, Object> productMainSheet = new HashMap<>();
        productMainSheet.put(NormalExcelConstants.CLASS, ProductMain.class);
        productMainSheet.put(NormalExcelConstants.PARAMS, productMainParam);
        //查询所有的商品主档
        QueryWrapper<XlProductInfo> queryWrapper = new QueryWrapper<>();
        //queryWrapper.eq("type","main");
        List<XlProductInfo> pageList = xlProductInfoService.list(queryWrapper);
        // 使用 Stream API 转换为 List<StudentVO>
        List<ProductMain> productMainList = pageList.stream()
                .map(productMainTemp -> new ProductMain(productMainTemp.getUpcCode(), productMainTemp.getProductName()))
                .collect(Collectors.toList());

        productMainSheet.put(NormalExcelConstants.DATA_LIST, productMainList);
        listMap.add(productMainSheet);

        //客户类型
        ExportParams xlCustomerTypePara = new ExportParams("客户类型", "导出人:" + sysUser.getRealname(),"客户类型");
        xlCustomerTypePara.setType(ExcelType.XSSF);
        Map<String, Object> xlCustomerTypeSheet = new HashMap<>();
        xlCustomerTypeSheet.put(NormalExcelConstants.CLASS, XlCustomerType.class);
        xlCustomerTypeSheet.put(NormalExcelConstants.PARAMS, xlCustomerTypePara);
        //查询所有的客户类型
        List<XlCustomerType> customerTypeList = customerTypeService.list();
        xlCustomerTypeSheet.put(NormalExcelConstants.DATA_LIST, customerTypeList);
        listMap.add(xlCustomerTypeSheet);


        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // Step.4 AutoPoi 导出Excel
        mv.addObject(NormalExcelConstants.FILE_NAME, "客户商品导入");//没用，前段会在设置
        mv.addObject(NormalExcelConstants.MAP_LIST,listMap);
        return mv;
    }

    private  boolean isAdmin(){
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //当前用户的角色
        String roles = sysUser.getRoleCode();

        boolean isAdmin =false;
        String [] s = {"slt_admin","admin"};
        if(StrUtil.containsAny(roles,s)){
            isAdmin = true;
        }
        return isAdmin;
    }
}
